#!/usr/bin/env perl

=head1 NAME

Google code jam

=cut

use strict;
use warnings;
use Text::CSV_XS;
use Data::Dumper;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init(
	{
		level => $INFO,
		file  => ">prob.log",
	},
	{
		level => $INFO,
		file  => "STDOUT",
	}
);

our ($T);
our @cases;

sub main() {
	load_data();
	write_output();
}

sub load_data() {
	my $filename = shift;
	my $csv      = make_csv_parser();
	open my $fh_in, "<:utf8", "input.txt"
	  or LOGDIE("$!");

	my $row = $csv->getline($fh_in);
	$T = $row->[0];

	#load cases
	for ( 1 .. $T ) {
		my $row = $csv->getline($fh_in);
		push @cases, $row->[0];
	}

	close($fh_in);
	INFO("Cases $T");
}

sub write_output() {
	local $\ = "\n";
	my $counter;
	open my $fh, ">:utf8", "output.txt" or LOGDIE "$!";

	for my $word (@cases) {
		INFO( ++$counter . "/" . $T . " " . $word );
		my $result = 0;
		my %seen;

		# determine base
		for my $char ( split( //, $word ) ) {
			$seen{$char} = undef;
		}
		my $base = scalar( keys %seen );
		$base = 2 if $base == 1;
		INFO "Lowest base is " . $base;

		# compute the number
		my $highest  = -1;
		my $position = length $word;
		while ( $word =~ /(.)/g ) {
			if ( not defined $seen{$1} ) {
				$highest++ if $highest == 1;
				$seen{$1} = abs($highest);
				$highest++;
			}
			# INFO $word . " " . $result . "+=" . $seen{$1} . "*" . $base . "**" . ( $position - 1 );
			$result += $seen{$1} * $base** --$position;
		}

		print $fh "Case #" . $counter . ": " . $result;
	}

	close $fh;
	INFO('DONE');
}

sub make_csv_parser {
	my $csv = Text::CSV_XS->new(
		{
			sep_char    => qq{ },
			quote_char  => qq{"},    # default
			escape_char => qq{"},    # default
			binary      => 1,

			# modified settings below
			blank_is_undef     => 1,
			allow_loose_quotes => 1,
		}
	);
}

sub check_parser_for_errors {
	my ( $csv_ref, $row_ref ) = @_;
	if ( !( defined $$row_ref ) and !( $$csv_ref->eof() ) ) {
		my $bad_argument = $$csv_ref->error_input();    # get the most recent bad argument
		my $diag         = $$csv_ref->error_diag();
		print "WARNING: CSV parser error <$diag> on line - $bad_argument.\n";
	}
}

=back

=cut

=head1 AUTHOR

Tomasz Adamusiak 2009

=cut

main();
